package com.ruoyi.car.business.service.impl;


import com.ruoyi.car.business.domain.BpmnInfo;
import com.ruoyi.car.business.domain.CarPackageAudit;
import com.ruoyi.car.business.domain.ServiceItem;
import com.ruoyi.car.business.mapper.ServiceItemMapper;
import com.ruoyi.car.business.query.ServiceItemQuery;
import com.ruoyi.car.business.service.IBpmnInfoService;
import com.ruoyi.car.business.service.ICarPackageAuditService;
import com.ruoyi.car.business.service.IServiceItemService;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.page.TablePageInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.ShiroUtils;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    ServiceItem newServiceItem1 = new ServiceItem();
    @Autowired
    private ServiceItemMapper serviceItemMapper;

    @Autowired
    private ICarPackageAuditService carPackageAuditService;

    @Autowired
    private IBpmnInfoService bpmnInfoService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        // 判断是否为空, 不为空才操作
        if (serviceItem != null) {
            // 创建一个新的变量接收前台新增数据 不接收不可修改数据
            newServiceItem1.setName(serviceItem.getName());
            newServiceItem1.setOriginalPrice(serviceItem.getOriginalPrice());
            newServiceItem1.setDiscountPrice(serviceItem.getDiscountPrice());
            newServiceItem1.setCarPackage(serviceItem.getCarPackage());
            newServiceItem1.setServiceCatalog(serviceItem.getServiceCatalog());
            newServiceItem1.setInfo(serviceItem.getInfo());
            newServiceItem1.setCreateTime(new Date());
            // 判断是否套餐
            if (ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage())) {
                // 不是套餐的把审核状态修改为初始化状态
                newServiceItem1.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
            }
            // 把新增数据设置为下架状态
            newServiceItem1.setSaleStatus(ServiceItem.SALESTATUS_OFF);
            // 把新增数据设置为不是软删除状态
            newServiceItem1.setIsDelete(ServiceItem.ISDELETE_NO);
            serviceItemMapper.insert(newServiceItem1);
        }
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        // 判断是否为空, 不为空才操作
        if (serviceItem != null) {
            ServiceItem oldServiceItem = this.get(serviceItem.getId());
            // 当处于上架状态不能编辑
            if (ServiceItem.SALESTATUS_ON.equals(oldServiceItem.getSaleStatus())) {
                throw new GlobalException("上架服务不能修改,请下架后再试");
            } else if (ServiceItem.AUDITSTATUS_AUDITING.equals(oldServiceItem.getAuditStatus())) {
                throw new GlobalException("服务正在审核不能修改");
            }

            // 审核通过将其状态变更为初始化
            if (ServiceItem.AUDITSTATUS_APPROVED.equals(oldServiceItem.getAuditStatus())) {
                oldServiceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
            }

            // 创建一个新的变量接收前台需要修改的数据 不接收不可修改数据
            oldServiceItem.setName(serviceItem.getName());
            oldServiceItem.setOriginalPrice(serviceItem.getOriginalPrice());
            oldServiceItem.setDiscountPrice(serviceItem.getDiscountPrice());
            oldServiceItem.setServiceCatalog(serviceItem.getServiceCatalog());
            oldServiceItem.setInfo(serviceItem.getInfo());

            serviceItemMapper.updateByPrimaryKey(oldServiceItem);
        }
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    @Override
    public void saleOn(Long id) {
        // 合理化校验
        ServiceItem oldObj = this.get(id);
        // 如果处于上架状态, 不需要做事情
        if (ServiceItem.SALESTATUS_ON.equals(oldObj.getSaleStatus())) {
            return;
        }
        // 处于非审核通过不进行上架操作
        if (!ServiceItem.AUDITSTATUS_APPROVED.equals(oldObj.getAuditStatus())
                && ServiceItem.CARPACKAGE_YES.equals(oldObj.getCarPackage())) {
            throw new GlobalException("未审核通过不运行上架");
        }
        serviceItemMapper.updateSaleStatus(id, ServiceItem.SALESTATUS_ON);
    }

    @Override
    public void saleOff(Long id) {
        serviceItemMapper.updateSaleStatus(id, ServiceItem.SALESTATUS_OFF);
    }

    @Override
    @Transactional
    public void startAudit(Long id, Long bpmnInfoId, Long director, Long finance, String info) {
        ServiceItem serviceItem = this.get(id);
        // 合理化校验
        if (!ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())) {
            // 如果不是套餐就返回非法操作
            throw new GlobalException("非法操作");
        }
        if (ServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus()) || //处于审核中
                ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus()) // 审核通过
        ) {
            throw new GlobalException("非法操作");
        }
        // 封装CarPackageAudit对象
        CarPackageAudit audit = new CarPackageAudit();
        audit.setServiceItemId(serviceItem.getId());
        audit.setServiceItemName(serviceItem.getName());
        audit.setServiceItemPrice(serviceItem.getDiscountPrice());
        audit.setServiceItemInfo(serviceItem.getInfo());
        audit.setCreator(ShiroUtils.getUserId().toString());
        audit.setBpmninfoId(bpmnInfoId);
        audit.setInfo(info);
        audit.setCreateTime(new Date());
        carPackageAuditService.save(audit);
        // 查询BpmnInfo
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        String definitionKey = bpmnInfo.getActProcessKey();
        String businessKey = audit.getId().toString();
        Map<String, Object> params = new HashMap<>();
        params.put("director",director);
        // 判断是否需要财务审批
        if (finance != null) {
            params.put("finance",finance);
        }
        params.put("discountPrice",serviceItem.getDiscountPrice().longValue());// 将BigDecimal转成Long类型
        // 启动流程获取到流程实例对象
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(definitionKey, businessKey, params);
        // 流程审核对象关联流程实例对象
        audit.setInstanceId(processInstance.getId());
        // 查询当前流程实例目前处在那个任务中
        Task currentTask = taskService.createTaskQuery()
                .processInstanceId(processInstance.getId())
                .singleResult();
        // 获取当前流程运行的节点, 获取这个几点处理人
        audit.setAuditorId(Long.parseLong(currentTask.getAssignee()));
        // 更新审核对象
        carPackageAuditService.update(audit);
        // 更新服务单项的状态
        serviceItemMapper.changeAuditStatus(serviceItem.getId(),ServiceItem.AUDITSTATUS_AUDITING);
    }

    @Override
    public void changeStatus(Long serviceItemId, Integer status) {
        serviceItemMapper.changeAuditStatus(serviceItemId,status);
    }
}
